import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { defineConfig, loadEnv } from 'vite';
import swc from 'vite-plugin-swc-transform';

export default defineConfig(({ mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  return {
    base: env.VITE_BASE_URL,
    plugins: [
      swc({
        swcOptions: {
          jsc: {
            target: 'es2020',
            transform: {
              legacyDecorator: true,
              decoratorMetadata: true,
              useDefineForClassFields: false,
              react: {
                runtime: 'automatic',
                importSource: 'vue-jsx-runtime',
              },
            },
            externalHelpers: true,
          },
        },
      }),
      vue(),
      vueJsx(),
    ],
    resolve: {
      alias: {
        '@': '/src',
      },
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('vant')) {
                return 'vant';
              }
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
            return undefined; // 在其他情况下，不创建单独的块
          },
        },
      },
      chunkSizeWarningLimit: 100,
    },
    server: {
      allowedHosts: ['local.bilibili.co'],
      port: 80,
      proxy: {
        '/prod-api/': {
          target: env.VITE_API_BASE,
          changeOrigin: true,
          ws: true,
          bypass(req) {
            req.headers.Referer = env.VITE_API_BASE;
            req.headers.Origin = env.VITE_API_BASE;
          },
        },
      },
    },
  };
});
